<template>
  <div class="search-container">
    <a-input-search class="search" placeholder="输入内容以搜索" search-button @search="search"/>
  </div>
  <a-row :gutter="24" style="margin:20px">
    <a-col :span="8" v-for="item in data" :key="item.id">
      <QuestionBank :icon-url="item.bankIcon" :item-id="item.id" :item-title="item.title" @click="editBankQuestion(item.id)"></QuestionBank>
    </a-col>
  </a-row>
  <div style="display: flex; justify-content: center; margin-top: 10px; margin-bottom: 10px;">
    <a-pagination
        :total="pageInfo.total"
        :current="pageInfo.current"
        :page-size="pageInfo.pageSize"
        :page-size-options="pageInfo.pageSizeOptions"
        show-jumper
        show-page-size
        @change="listQuestionBank"
        @page-size-change="changePageSize"
    />
  </div>
  <a-modal
      v-model:visible="confirmVisible"
      @ok="doDeleteBank"
      :closable="false"
  >
    <div style="text-align: center">
      确认删除？
    </div>
  </a-modal>

  <!-- 弹窗展示题目的修改 -->
  <a-modal :width="1200" :visible="infoVisible" @ok="doEdit" @cancel="cancelEdit">
    <template #title>
      {{ editBankInfo.title }}
    </template>
    <a-list :scrollbar="scrollbar" :bordered="false" :split="false">
      <!-- 选择题区域 -->
      <a-list-item v-for="(item,index) in selectQuestions" :key="item.id">
        <!-- <a-list>定义了滚动列表下的每一个题目-->
        <SelectQuestion
            :id="item.id"
            :index="index"
            :options="item.options"
            :title="(index + 1) + '.' + item.content"
            :default-value="item.answer"
            :disabled="true"
            :editable="true"
            :key="item.answer"
            @delete-question="deleteSelectQuestion"
            @edit-question="editSelectQuestion"
        >
        </SelectQuestion>
      </a-list-item>
      <!-- 判断题区域 -->
      <a-list-item v-for="(item,index) in judgeQuestions" :key="item.id">
        <!-- <a-list>定义了滚动列表下的每一个题目-->
        <JudgeQuestion
            :title="(index + 1 + selectQuestions.length)+'.'+item.content"
            :id="item.id"
            :index="index"
            :default-value="item.isCorrect.toString()"
            :disabled="true"
            :editable="true"
            :key="item.isCorrect.toString()"
            @delete-question="deleteJudgeQuestion"
            @edit-question="editJudgeQuestion"
        >
        </JudgeQuestion>
      </a-list-item>
      <a-list-item>
        <a-button type="primary" @click="addQuestion">添加题目</a-button>
      </a-list-item>
    </a-list>
  </a-modal>

  <a-modal :width="800" :visible="addVisible" @ok="submitQuestionInfo" @cancel="addVisible=false">
    <!-- 为 a-form 添加 ref 属性 -->
    <a-form
        ref="questionFormRef"
        :model="questionInfo"
        :style="{width:'600px' , marginLeft: '100px'}"
        label-align="left"
        scroll-to-first-error
        size="large"
    >
      <!-- 选择题目类型 -->
      <a-form-item label="题目类型" :content-flex="false" :merge-props="false">
        <a-form-item
            field="type"
            validate-trigger="input"
            :rules="[{ required: true, message: '必须选择题目类型！'}]"
            hide-label>
          <a-select v-model="questionInfo.type" :style="{width:'320px'}" placeholder="选择题目类型">
            <a-option :value="0">选择题</a-option>
            <a-option :value="1">判断题</a-option>
          </a-select>
        </a-form-item>
      </a-form-item>
      <!--题目标题-->
      <a-form-item v-if="questionInfo.type !== ''" label="题目标题" :content-flex="false" :merge-props="false">
        <a-form-item
            field="content"
            validate-trigger="input"
            :rules="[{ required: true, message: '题干不能为空！'}]"
            hide-label>
          <a-input v-model="questionInfo.content"/>
        </a-form-item>
      </a-form-item>
      <!--题目选项-->
      <a-form-item v-if="questionInfo.type===0" label="题目选项" :content-flex="false" :merge-props="false">
            <a-radio-group
                field="answer"
                v-model="questionInfo.answer"
                direction="vertical"
                :default-value="questionInfo.answer"
            >
              <a-radio
                  v-for="(option , index) in questionInfo.options"
                  :key="option.key"
                  :value="option.key"
                  style="margin-bottom: 30px"
              >
                <a-form-item
                    :field="'options['+index+'].key'"
                    validate-trigger="input"
                    :rules="[{ required: true, message: '选项内容不能为空！'}]"
                    hide-label
                    style="margin-bottom: 0;"
                >
                  <a-space>
                    {{ option.key }}.
                    <a-input style="width: 360px" v-model="questionInfo.options[index].value"/>
                  </a-space>
                </a-form-item>
              </a-radio>
            </a-radio-group>
      </a-form-item>
      <a-form-item v-if="questionInfo.type===1" label="是否正确" :content-flex="false" :merge-props="false">
        <a-form-item
            field="isCorrect"
            validate-trigger="input"
            :rules="[{ required: true, message: '选项内容不能为空！'}]"
            hide-label
            style="margin-bottom: 0;"
        >
          <a-switch style="margin-right: 10px" v-model="questionInfo.isCorrect"/>
          {{ questionInfo.isCorrect ? '是' : '否' }}
        </a-form-item>
      </a-form-item>
    </a-form>
  </a-modal>
  <!--添加题目-->
  <a-modal :width="800" :visible="editVisible" @ok="submitQuestionInfo" @cancel="editVisible=false">
    <!-- 为 a-form 添加 ref 属性 -->
    <a-form
        ref="questionFormRef"
        :model="questionInfo"
        :style="{width:'600px' , marginLeft: '100px'}"
        label-align="left"
        scroll-to-first-error
        size="large"
    >
      <!--题目标题-->
      <a-form-item label="题目标题" :content-flex="false" :merge-props="false">
        <a-form-item
            field="content"
            validate-trigger="input"
            :rules="[{ required: true, message: '题干不能为空！'}]"
            hide-label>
          <a-input v-model="questionInfo.content"/>
        </a-form-item>
      </a-form-item>
      <!--题目选项-->
      <a-form-item v-if="questionInfo.type===0" label="题目选项" :content-flex="false" :merge-props="false">
            <a-radio-group field="answer" v-model="questionInfo.answer" direction="vertical"
                           :default-value="questionInfo.answer">
              <a-radio
                  v-for="(option , index) in questionInfo.options"
                  :key="option.key"
                  :value="option.key"
                  style="margin-bottom: 30px"
              >
                <a-form-item
                    :field="'options['+index+'].key'"
                    validate-trigger="input"
                    :rules="[{ required: true, message: '选项内容不能为空！'}]"
                    hide-label
                    style="margin-bottom: 0;"
                >
                  <a-space>
                    {{ option.key }}.
                    <a-input style="width: 360px; line-height: 32px;"
                             v-model="questionInfo.options[index].value"/>
                  </a-space>
                </a-form-item>
              </a-radio>
            </a-radio-group>
      </a-form-item>
      <a-form-item v-if="questionInfo.type===1" label="是否正确" :content-flex="false" :merge-props="false">
        <a-form-item
            field="isCorrect"
            validate-trigger="input"
            :rules="[{ required: true, message: '选项内容不能为空！'}]"
            hide-label
            style="margin-bottom: 0;"
        >
          <a-switch style="margin-right: 10px" v-model="questionInfo.isCorrect"/>
          {{ questionInfo.isCorrect ? '是' : '否' }}
        </a-form-item>
      </a-form-item>
    </a-form>
  </a-modal>


</template>

<script setup>
import {onMounted, ref} from "vue";
import {
  getQuestionBankVOByIdUsingGet,
  listQuestionBankByPageUsingPost
} from "@/api/QuestionBankRequest";
import QuestionBank from "@/components/QuestionBank.vue";
import {
  addQuestionUsingPost,
  adminQuestionUsingPost, deleteQuestionUsingPost,
  getQuestionByBankId, getQuestionVOByIdUsingGet,
} from "@/api/QuestionRequest";
import SelectQuestion from "@/components/SelectQuestion.vue";
import JudgeQuestion from "@/components/JudgeQuestion.vue";
import message from "@arco-design/web-vue/es/message";
// 题库列表
const data = ref([]);

// 搜索框输入的内容
const inputContent = ref("")
// 分页配置信息
const pageInfo = ref({
  pageSize: 6,
  current: 1,
  total: 50,
  pageSizeOptions: [6, 12, 18, 24],
});

// 当前正在修改的题目，是从题目列表中提取出的对象
const editQuestion = ref({});
// 提示框是否展示
let confirmVisible = ref(false);
// 修改框是否展示
let infoVisible = ref(false);
// 题目修改框是否显示
const editVisible = ref(false);
// 题目添加框是否显示
const addVisible = ref(false);
// 表单ref对象
const questionFormRef = ref();
// 当前正在修改的题库信息
let editBankInfo = ref({});
// 题目列表
let selectQuestions = ref([]);
let judgeQuestions = ref([]);
// 当前操作的题目下标
const questionIndex = ref(0);

// 定义当前操作的请求
let questionUpdateRequest = [];
let questionDeleteRequest = {ids: []}

// 记录新加的题目ID，若用户取消操作则进行删除
let questionDeleteNewRequest = {ids: []}

// 设置当前的操作类型
let operateType = 'update';

// 获取题库信息
onMounted(async () => {
  await listQuestionBank(1);
})

/**
 * 表单填写的题库信息
 * @param current
 * @returns {Promise<void>}
 */
// 当前正在输入的题目变更数据

const questionInfo = ref({
  id: -1,
  content: '',
  options: [
    {key: 'A', value: ''},
    {key: 'B', value: ''},
    {key: 'C', value: ''},
    {key: 'D', value: ''},
  ],
  type: '',
  answer: '',
  isCorrect: true,
});

// 获取题库信息的具体方法
async function listQuestionBank(current) {
  const result = await listQuestionBankByPageUsingPost({
    current: current,
    pageSize: pageInfo.value.pageSize,
    searchText: inputContent.value
  });
  pageInfo.value.current = current;
  pageInfo.value.total = result.data.data.total;
  data.value = result.data.data.records;
}


function search(content) {
  inputContent.value = content;
  listQuestionBank(1);
}

async function changePageSize(pageSize) {
  pageInfo.value.pageSize = pageSize;
  await listQuestionBank(pageInfo.value.current);
}

// 进行删除操作
async function doDeleteBank() {
  if (questionInfo.value.type === 0) {
    // 选择题
    if (questionIndex.value >= 0 && questionIndex.value < selectQuestions.value.length) {
      selectQuestions.value.splice(questionIndex.value, 1);
    }
  } else if (questionInfo.value.type === 1) {
    // 判断题
    if (questionIndex.value >= 0 && questionIndex.value < judgeQuestions.value.length) {
      judgeQuestions.value.splice(questionIndex.value, 1);
    }
  }
  questionDeleteRequest.ids.push(questionInfo.value.id);
  console.log(questionDeleteRequest);
  questionInfo.value.id = 0;
  confirmVisible.value = false;
}

// 清空弹窗的内容
async function cancelEdit() {
  if (questionDeleteNewRequest.ids.length > 0) {
    await deleteQuestionUsingPost(questionDeleteNewRequest);
  }
  infoVisible.value = false;
}

function clearContent(){
  editBankInfo.value = {};
  selectQuestions.value = [];
  judgeQuestions.value = [];
  questionUpdateRequest = [];
  questionDeleteRequest.ids = [];
  questionDeleteNewRequest.ids = [];
}

// 完成最后的请求调用
async function doEdit() {
  editBankInfo.value = {};
  selectQuestions.value = [];
  judgeQuestions.value = [];
  infoVisible.value = false;
  if (questionDeleteRequest.ids.length === 0 && questionUpdateRequest.length === 0 && questionDeleteNewRequest.length === 0) {
    return;
  }

  let result = await adminQuestionUsingPost({
    updateRequest: questionUpdateRequest,
    deleteRequest: questionDeleteRequest,
  });
  if (result.data.code !== 0) {
    message.error('更新错误，请联系爱编程的石头解决问题T_T......');
  } else {
    message.success('更新成功^_^~');
  }
  questionUpdateRequest = [];
  questionDeleteRequest.ids = [];
  questionDeleteNewRequest.ids = [];
}

async function editBankQuestion(bankId) {
  clearContent();
  const bankInfo = await getQuestionBankVOByIdUsingGet(bankId);
  editBankInfo.value = bankInfo.data.data;
  // 获取当前题库的所有题目信息
  const result = await getQuestionByBankId(bankId);
  result.data.data.forEach((item) => {
    if (item.type === 0) {
      selectQuestions.value.push(item);
    } else if (item.type === 1) {
      judgeQuestions.value.push(item);
    }
  })
  infoVisible.value = true;
}

function deleteSelectQuestion(questionId, index) {
  operateType = 'delete';
  confirmVisible.value = true;
  questionInfo.value.type = 0;
  questionIndex.value = index;
  questionInfo.value.id = questionId;
}

function editSelectQuestion(questionId, index) {
  operateType = 'update';
  questionInfo.value.type = 0;
  questionIndex.value = index;
  editQuestion.value = selectQuestions.value[index];
  questionInfo.value.id = questionId;
  // 初始化 questionInfo.options
  questionInfo.value.options = [];
  questionInfo.value.options = editQuestion.value.options;
  questionInfo.value.content = editQuestion.value.content;
  questionInfo.value.answer = editQuestion.value.answer;
  editVisible.value = true;
}

function deleteJudgeQuestion(questionId, index) {
  operateType = 'delete';
  confirmVisible.value = true;
  questionInfo.value.type = 1;
  questionIndex.value = index;
  questionInfo.value.id = questionId;
}

function editJudgeQuestion(questionId, index) {
  operateType = 'update';
  questionInfo.value.type = 1;
  questionIndex.value = index;
  editQuestion.value = judgeQuestions.value[index];
  questionInfo.value.id = questionId;
  questionInfo.value.content = editQuestion.value.content;
  questionInfo.value.isCorrect = editQuestion.value.isCorrect === 1;
  editVisible.value = true;
}

// 确认后修改题目的内容
async function submitQuestionInfo() {
  questionFormRef.value.validate(async (valid) => {
    if (valid) {
      message.error("表单填写错误，请重新检查！");
      return;
    }
    let question = {
      content: questionInfo.value.content,
      tags: questionInfo.value.tags,
      type: questionInfo.value.type,
      options: questionInfo.value.options,
      answer: questionInfo.value.answer,
      isCorrect: questionInfo.value.isCorrect ? 1 : 0
    };
    if (question.type === 1) {
      question.answer = question.isCorrect === 1 ? '正确' : '错误';
    }
    if (operateType === 'update') {
      // 校验通过，进行赋值操作
      editQuestion.value.content = questionInfo.value.content;
      editQuestion.value.options = questionInfo.value.options;
      editQuestion.value.answer = questionInfo.value.answer;
      editQuestion.value.isCorrect = questionInfo.value.isCorrect ? 1 : 0;
      editVisible.value = false;
      question['id'] = questionInfo.value.id;
      // 记录当前修改的内容为修改请求
      questionUpdateRequest.push(question);
      console.log(questionUpdateRequest);
    } else if (operateType === 'add') {
      question['questionBankId'] = editBankInfo.value.id;
      const result = await addQuestionUsingPost(question);
      console.log(result.data.data);
      const newQuestion = await getQuestionVOByIdUsingGet(result.data.data);
      if (question.type === 0) {
        selectQuestions.value.push(newQuestion.data.data);
      } else if (question.type === 1) {
        judgeQuestions.value.push(newQuestion.data.data);
      }
      addVisible.value = false;
      questionDeleteNewRequest.ids.push(result.data.data);
    }
    resetQuestionInfo();
  });
}

function addQuestion() {
  resetQuestionInfo();
  addVisible.value = true;
  operateType = 'add';
}

function resetQuestionInfo() {
  questionInfo.value = {
    id: -1,
    content: '',
    options: [
      {key: 'A', value: ''},
      {key: 'B', value: ''},
      {key: 'C', value: ''},
      {key: 'D', value: ''},
    ],
    type: '',
    answer: '',
    isCorrect: true,
  }
}

</script>

<style scoped>
/* 搜索框样式 */
.search {
  width: 360px;
}

/* 搜索框容器样式 */
.search-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}
</style>